
from rest_framework.generics import ListAPIView
from renranapi.settings import constants
from .models import Banner
from datetime import datetime
from .serializers import BannerModelSerializer
class BannerListAPIView(ListAPIView):
    queryset = Banner.objects.filter(
        is_show=True,
        is_delete=False,
        start_time__lte=datetime.now(),
        end_time__gte=datetime.now()).order_by("orders","-id")[:constants.HOME_BANNER_LENGTH]
    serializer_class = BannerModelSerializer

from .models import Nav
from .serializers import NavModelSerializer
class NavHeaderListAPIView(ListAPIView):
    queryset = Nav.objects.filter(is_show=True, is_delete=False, option=1,pid=None).order_by("orders","-id")[:constants.HEADER_NAV_LENGTH]
    serializer_class = NavModelSerializer

class NavFooterListAPIView(ListAPIView):
    queryset = Nav.objects.filter(is_show=True, is_delete=False, option=2,pid=None).order_by("orders","-id")[:constants.FOOTER_NAV_LENGTH]
    serializer_class = NavModelSerializer

from article.models import Article
from .serializers import ArticleModelSerializer
from .paginations import HomeArticlePageNumberPagination
from users.models import User
from renranapi.utils.tablestore import OTS
from renranapi.settings import constants

class ArticleListAPIView(ListAPIView):
    serializer_class = ArticleModelSerializer
    pagination_class = HomeArticlePageNumberPagination

    def get_queryset(self):
        user = self.request.user
        queryset = []
        if isinstance(user, User):
            """登录用户"""
            # 获取未读池中上一次阅读的主键ID
            ots = OTS()
            result = ots.get_last_id(user.id)
            last_sequence_id=result.get("last_sequence_id")
            # 根据上一次推送的主键ID拉去Feed流
            if last_sequence_id is not None:
                import json
                last_id = json.loads(last_sequence_id)
                sequence_id = last_id.get("sequence_id")
                sender_id = last_id.get("sender_id")
                message_id = last_id.get("message_id")
                new_last_id,feed_list = ots.pull_feed(user.id,sequence_id,sender_id,message_id,limit=constants.HOME_ARTICLE_LENGTH)
            else:
                new_last_id,feed_list = ots.pull_feed(user.id,limit=constants.HOME_ARTICLE_LENGTH)

            ots.update_last_id(user.id, new_last_id, last_sequence_id)
            # 给予feed_list的文章id列表到数据库中查询文章
            if len(feed_list)>0:
                """直接到数据库查询文章内容返回"""
                queryset = Article.objects.filter(is_public=True, id__in=feed_list)

        """未登录用户"""
        if len(queryset) < 1:
            queryset = Article.objects.filter(is_public=True).order_by("-reward_count", "-comment_count", "-like_count",
                                                                     "-id")
        return queryset